<template>
  <div class="tally-show">
    <!-- 头部区域 -->
    <div class="header-section">
      <div class="header-left">
        <h2>财务记账</h2>
      </div>
     
    </div>

    <!-- 数据筛选区域 -->
    <div class="filter-section">
      <h3>数据筛选</h3>
      <el-form :inline="true" :model="filters" class="filter-form" size="small">
      <el-form-item label="流水号:">
        <el-input v-model="filters.SerialNumber" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="名称:">
        <el-input v-model="filters.ProductName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="财务类别:">
        <el-select v-model="filters.PayMentType" placeholder="请选择" style="width: 160px" clearable>
        <el-option label="请选择" value="" />
              <el-option label="微信" value="微信" />
               <el-option label="支付宝" value="支付宝" />
                <el-option label="建设银行" value="建设银行" />
        </el-select>
      </el-form-item>
      <el-form-item label="起止时间:">
        <el-date-picker
          v-model="filters.StartTime"
          type="date"
          placeholder="开始时间"
          clearable
        />
        <span style="margin: 0 8px;">~</span>
        <el-date-picker
          v-model="filters.EndTime"
          type="date"
          placeholder="结束时间"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    </div>

    <!-- 数据列表区域 -->
    <div class="data-section">
      <h3>数据列表</h3>
             <!-- 数据表格上方右侧按钮 -->
       <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
         <el-button size="small" @click="handleRefresh">刷新</el-button>
         <el-button size="small" style="margin-left: 10px;" @click="handleExport">导出</el-button>
       </div>
      <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      @selection-change="onSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="serialNumber" label="流水号" width="120" />
      <el-table-column prop="productName" label="名称" width="170" />
      <el-table-column prop="payMentType" label="分类" width="100" />
      <el-table-column prop="payer" label="收款方/付款方" width="120" />
      <el-table-column prop="type" label="类型" width="80" />
      <el-table-column prop="paymentAmount" label="付款金额" width="100" />
      <el-table-column prop="createTime" label="付款时间" width="160" :formatter="formatDateTime" />
      <el-table-column prop="payMentType" label="付款方式" width="100" />
      <el-table-column prop="paymentInstitution" label="付款机构" width="80" />
      
    </el-table>

    </div>

    <!-- 底部操作区域 -->
    <div class="bottom-section">
      <div class="bottom-left">
        <el-checkbox v-model="selectAll" @change="onSelectAll">全选</el-checkbox>
        <el-button size="small" style="margin-left: 10px;" @click="onBatchDelete" :disabled="!selectedRows.length">批量删除</el-button>
      </div>
      <div class="bottom-right">
        <el-pagination
          v-model:current-page="Page.PageIndex"
          v-model:page-size="Page.PageSize"
          :page-sizes="[15, 20, 30, 50]"
          layout="total, prev, pager, next, sizes"
          :total="Page.totalCount"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { FinanceRed, FinanceWrite } from '@/http/axiosHelper'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'


const filters = ref({
  SerialNumber: '',
  ProductName: '',
  PayMentType: '',
  StartTime: '',
  EndTime: ''
})

const tableData = ref([
  // 这里填充你的表格数据，示例：
  {
    serialNumber: '',
    productName: '',
    payMentType: '',
    payer: '',
    type: '',
    paymentAmount: '',
    method: '',
    createTime: '',
    paymentInstitution: '',
  },
  // ...更多数据
])
const Page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
})

const selectedRows = ref([])
const selectAll = ref(false)
const invertSelect = ref(false)
const batchAction = ref('')
const tableRef = ref(null)


// 格式化时间的方法
function formatDateTime(row, column, cellValue) {
  if (cellValue) {
    return cellValue.replace('T', ' ')
  }
  return cellValue
}

// 获取记账数据的方法
async function getTallyData() {
  // 处理时间参数，确保包含所选日期
  let startTime = filters.value.StartTime
  let endTime = filters.value.EndTime
  
  // 如果有开始时间，设置为当天的开始时间（00:00:00）
  if (startTime) {
    const startDate = new Date(startTime)
    startDate.setHours(0, 0, 0, 0)
    startTime = startDate.toISOString()
  }
  
  // 如果有结束时间，设置为当天的结束时间（23:59:59）
  if (endTime) {
    const endDate = new Date(endTime)
    endDate.setHours(23, 59, 59, 999)
    endTime = endDate.toISOString()
  }

  FinanceRed.get("/api/Tally/GetTally",{params:
    {
        SerialNumber: filters.value.SerialNumber,
      ProductName: filters.value.ProductName,
      PayMentType: filters.value.PayMentType,
      StartTime: startTime,
      EndTime: endTime,
      PageIndex: Page.PageIndex,
      PageSize: Page.PageSize
    }}).then(res=>
  {
    tableData.value = res.data.pageData 
    Page.totalCount=res.data.totalCount
  })
}

// 页面加载时获取数据
onMounted(() => {
  getTallyData()
})

function onSearch() {
  Page.PageIndex = 1 // 重置到第一页
  getTallyData()
}

function onReset() {
  filters.value = {
    SerialNumber: '',
    ProductName: '',
    PayMentType: '',
    StartTime: '',
    EndTime: ''
  }
  Page.PageIndex = 1
  getTallyData()
}

function onSelectionChange(val) {
  selectedRows.value = val
  // 更新全选状态
  selectAll.value = val.length === tableData.value.length && tableData.value.length > 0
}

function onSelectAll(val) {
  // 全选逻辑
  if (val) {
    // 选中所有数据
    tableData.value.forEach(row => {
      tableRef.value.toggleRowSelection(row, true)
    })
  } else {
    // 取消所有选中
    tableRef.value.clearSelection()
  }
}


// 批量删除
function onBatchDelete() {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条数据吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 批量删除接口，假设后端支持批量删除
      const ids = selectedRows.value.map(item => item.id)
      FinanceWrite.delete('/api/Management/BatchDeleteManagement', { data: { id: ids.join(',') } })
        .then(res => {
          if (res.data.code === 200) {
            ElNotification({
              title: '批量删除成功',
              message: '批量删除成功',
              type: 'success',
              position: 'bottom-right'
            });
            getTallyData()
          } else {
            ElMessage.error(res.data.msg || '批量删除失败')
          }
        })
        .catch(() => {
          ElMessage.error('批量删除失败，网络或服务器异常')
        })
    })
    .catch(() => {
      // 用户取消，无需操作
    })
}



function onPageSizeChange(size) {
  Page.PageSize = size
  Page.PageIndex = 1
  getTallyData()
}

function onPageChange(page) {
  Page.PageIndex = page
  getTallyData()
}

// 刷新方法
function handleRefresh() {
  // 重置筛选条件
  filters.value = {
    SerialNumber: '',
    ProductName: '',
    PayMentType: '',
    StartTime: '',
    EndTime: ''
  }
  // 重置分页
  Page.PageIndex = 1
  Page.PageSize = 15
  // 清空选中状态
  selectedRows.value = []
  selectAll.value = false
  // 重新获取数据
  getTallyData()
  // 显示刷新提示
  ElMessage.success('页面已刷新')
}

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 处理时间参数，确保包含所选日期
        let startTime = filters.value.StartTime
        let endTime = filters.value.EndTime
        
        // 如果有开始时间，设置为当天的开始时间（00:00:00）
        if (startTime) {
            const startDate = new Date(startTime)
            startDate.setHours(0, 0, 0, 0)
            startTime = startDate.toISOString()
        }
        
        // 如果有结束时间，设置为当天的结束时间（23:59:59）
        if (endTime) {
            const endDate = new Date(endTime)
            endDate.setHours(23, 59, 59, 999)
            endTime = endDate.toISOString()
        }

        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await FinanceRed({
            url: '/api/Tally/GetTallyExport', // 后端接口地址
            method: 'GET',
            params: {
                SerialNumber: filters.value.SerialNumber,
                ProductName: filters.value.ProductName,
                PayMentType: filters.value.PayMentType,
                StartTime: startTime,
                EndTime: endTime,
                PageIndex: Page.PageIndex,
                PageSize: Page.PageSize
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        // 5. 显示成功提示
        ElNotification({
            title: '导出成功',
            message: '文件已成功导出',
            type: 'success',
            position: 'bottom-right'
        });

    } catch (error) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '财务记账.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '财务记账.xlsx';
}
</script>

<style scoped>
.tally-show {
  padding: 20px;
  background: #fff;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.header-left h2 {
  margin: 0;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.filter-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.filter-form {
  margin-bottom: 0;
}

.data-section {
  margin-bottom: 20px;
}

.data-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.bottom-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.bottom-left {
  display: flex;
  align-items: center;
}

.bottom-right {
  display: flex;
  align-items: center;
}
</style>
